package org.jeecg.common.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.jpush.api.push.model.Options;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jeecg.common.constant.CommonConstant;

import cn.jiguang.common.ClientConfig;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import org.springframework.beans.factory.annotation.Value;

/**
 * 极光推送工具类
 *
 * @PROJECT_NAME: viewlife
 * @author: lixiao
 * @version: V1.0
 * @Date: 2017/1/10
 * @Description:
 */
public class JPushClientUtil {
	private static JPushClient jPushClient;

	public static final String PUSH_SUCC = "success";
	public static final String PUSH_FAIL = "推送失败";
//	public static final String PREFIX = "userT_"; //测试版前缀
//	public static final String PREFIX = "user_";	//正式版前缀

	// 从配置文件推送的前缀
	@Value("${xinfu.jiguang.prefix}")
	private static String jpushPrefix;
	
	/**
	 * 初始化 JPushClient
	 *
	 * @return
	 */
	private static JPushClient getjPushClient() {
		if (jPushClient == null) {
			ClientConfig clientConfig = ClientConfig.getInstance();
			clientConfig.setTimeToLive(86400);
			jPushClient = new JPushClient(CommonConstant.MASTER_SECRET, CommonConstant.APP_KEY, null, clientConfig);
		}

		return jPushClient;

	}

	public static JPushClientUtil newBuilder() {
		return new JPushClientUtil();
	}

	/**
	 * 构建推送对象 单点推送（精确推送）
	 *
	 * @param arrUsers
	 * @param strContent
	 * @return
	 */
	private static PushPayload getPushPayloadToUser(List<String> arrUsers, String title, String strContent,
			Map<String, String> extras) {

		Audience audience = Audience.tag(arrUsers);
		// Notification notification = Notification.android(strContent,
		// "title测试", extras);

		return PushPayload.newBuilder().setPlatform(Platform.all())
				//APns的推送环境为生产环境
				.setOptions(Options.newBuilder().setApnsProduction(true).build())
				.setAudience(audience)//
				.setNotification(Notification.newBuilder() //
						.addPlatformNotification(AndroidNotification.newBuilder() //
								.addExtras(extras) //
								.setAlert(strContent) //
								.setTitle(title) //
								.build()) //
						.addPlatformNotification(IosNotification.newBuilder() //
								.addExtras(extras) //
								.setSound("default")
								.setAlert(strContent.toString()) //
								.build()) //
						.build()) //
				.build(); //
		// return
		// PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.tag(arrUsers)).setNotification(Notification.alert(strContent)).build();
	}

	/**
	 * 构建推送对象 全部推送
	 *
	 * @param strContent
	 * @return
	 */
	private static PushPayload getPushPayloadToAll(String strContent) {

		return PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.all())
				.setNotification(Notification.alert(strContent)).build();

	}

	/**
	 * 开放接口，精确到用户(List格式)
	 * 
	 * @param arrUserIds
	 * @param strContent
	 * @return
	 */
	public static String pushMessageToUser(List<String> arrUserIds, String title, String strContent,
			Map<String, String> extras) {
		// 初始化jPushClient
		JPushClient jPushClient = getjPushClient();

		// 构建要推送的用户
		List<String> pushUsers = new ArrayList<String>();

		if (arrUserIds != null) {
			for (int i = 0; i < arrUserIds.size(); i++) {
				pushUsers.add(jpushPrefix + arrUserIds.get(i));
			}
		}

		// 构建推送的对象
		PushPayload pushPayload = getPushPayloadToUser(pushUsers, title, strContent, extras);

		return strutsPushAndReturnResult(jPushClient, pushPayload);

	}

	/**
	 * 开放接口，精确到用户(单个格式)
	 * 
	 * @param arrUserId
	 * @param strContent
	 * @return
	 */
	public static String pushMessageToUser(String arrUserId, String title, String strContent,
			Map<String, String> extras) {
		// 初始化jPushClient
		JPushClient jPushClient = getjPushClient();

		// 构建要推送的用户
		List<String> pushUsers = new ArrayList<String>();

		if (arrUserId != null) {
			System.out.println(jpushPrefix + arrUserId);
			pushUsers.add(jpushPrefix + arrUserId);
		}
		// 构建推送的对象
		PushPayload pushPayload = getPushPayloadToUser(pushUsers, title, strContent, extras);

		return strutsPushAndReturnResult(jPushClient, pushPayload);

	}

	/**
	 * 开放接口 给所有用户推送消息
	 * 
	 * @param strContent
	 * @return
	 */
	public static String pushMessageToAll(String strContent) {
		// 初始化jPushClient
		JPushClient jPushClient = getjPushClient();

		// 构建推送的对象
		PushPayload pushPayload = getPushPayloadToAll(strContent);

		return strutsPushAndReturnResult(jPushClient, pushPayload);
	}

	private static String strutsPushAndReturnResult(JPushClient jPushClient, PushPayload pushPayload) {
		PushResult result = null;
		try {
			// 开始发送
			result = jPushClient.sendPush(pushPayload);
		} catch (Exception e) {
			/**
			 * 处理异常
			 */
			String errorMsg = "极光推送发生错误，请查看出错的原因";
			Log log = LogFactory.getLog(JPushClientUtil.class);
			log.error(errorMsg, e);
			return "99";

		}
		return result.statusCode + "";
	}

	public static void main(String[] args) {

		pushMessageToUser("1170835f617642e391429e2f8d1dc04e", "推送bbb", "haha", null);
		/*
		 * PushResult result = null; JPushClient jPushClient = getjPushClient();
		 * List<String> param = new ArrayList<String>();dbe4bb1621d448178b8d0fe1722e1b0f
		 */
		// sendPush("5fe73f02bf7c4915b4a998782d56cb4f", "极光推送测试");
		/*
		 * param.add("user_" + "5fe73f02bf7c4915b4a998782d56cb4f");
		 * 
		 * PushPayload pushPayload = getPushPayloadToUser(param, "极光推送测试"); try
		 * { result = jPushClient.sendPush(pushPayload);
		 * 
		 * } catch (APIConnectionException e) {
		 * System.out.println("APIConnectionException"); e.printStackTrace(); }
		 * catch (APIRequestException e) {
		 * System.out.println("APIRequestException"); e.printStackTrace();
		 * }finally{ System.out.println(result); }
		 */
		
//		System.out.println(String.format(ActUtils.SMS_PD_END, "张三","haha"));
	}

}
